package plugin;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.sql.SQLException;
import java.sql.Statement;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import dataPersistence.TransactionManager;

public class NathanPlugin implements IBarcodeFinder {

	private static final int timeoutMillis = 3000;

	private String description;
	private String url;


	public NathanPlugin()
	{
		url = "http://www.upcdatabase.com/item/";
		description="";

	}
	@Override
	public String getDescription(String barcode) 
	{
		String searchURL =url +barcode;

		try 
		{
			URL pageURL = new URL(searchURL);

			Document doc = Jsoup.parse(pageURL, timeoutMillis);
			Element table = doc.select(".data").first();
			if(table==null)
				return "";
			Elements descriptionElement = table.select(":containsOwn(Description)");
			description=descriptionElement.first().nextElementSibling().nextElementSibling().ownText();

			return description;

		}
		catch (NullPointerException e)
		{
			return "";
		}
		catch (IOException e) 
		{
			System.err.println("timeout");
			return "";
			//e.printStackTrace();
		}
	}




//	public static void main(String[] var)
//	{
//		String[] barcodes={"9217535026035","0836930033098","0094000728569","0015400127950",
//				"0781241401282","0074345175211","0074319652274","4792210100163","0638940836535",
//				"0829352488935","0639277003973","0609728281908","0615755559712","0639277398338",
//				"0609728281892","0608940544990","0153091000074","0812616012861","0052883005955",
//				"0888822220710"};
//		NathanPlugin plugin = new NathanPlugin();
//		for(String str:barcodes)
//		{
//			String tmp=plugin.getDescription(str);
//			if(tmp.isEmpty())
//				System.err.println("error on barcode "+str);
//			else
//				System.out.println("Barcode: "+str+" Description: "+tmp);
//		}	
//		//TransactionManager.createDB();
//		TransactionManager.initialize();
//		TransactionManager.createDB();
//		
//		
//	}

}
